/**
 * @description 公共 router
 */
const router = require('koa-router')()
const koaForm = require('formidable-upload-koa')
const { SuccessModel, ErrorModel } = require('../model/ResModel')
const { PROVINCE_CITY } = require('../constants/province');
const loginCheck = require('../middlewares/loginCheck')
const { saveFile } = require('../controller/shared')

router.prefix('/api/shared')

/**
 * 获取省份列表
 */
router.get('/province', async (ctx, next) => {
  const provinceList = PROVINCE_CITY.map(p => ({
    id: p.id,
    name: p.name
  }))
  ctx.body = new SuccessModel(provinceList);
})

/**
 * 获取城市列表
 */
router.get('/city', async (ctx, next) => {
  const { provinceId } = ctx.request.query
  const targetProvince = PROVINCE_CITY.find(p => p.id === Number(provinceId));

  if (!targetProvince) {
    ctx.body = new ErrorModel({ errno: -1, message: '所查省份不存在，请检查是否传递了正确的省份 ID' })
  } else {
    ctx.body = new SuccessModel(targetProvince.cities);
  }
})

/**
 * 文件上传 - 上传用户头像
 * @param {binary} file 文件对象
 */
router.post('/uploadPortrait', loginCheck, koaForm(), async (ctx, next) => {
  // 获取前端传来的文件，其中 file 字段取决于前端传参
  const file = ctx.req.files['file']
  const { type, name, path, size } = file
  
  ctx.body = await saveFile({ type, name, filePath: path, size }, 'portrait')
})

module.exports = router
